package com.hro.hro_app.dataController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.hro.hro_app.appControler.DownloadRoosterTask;
import com.hro.hro_app.database.DBManager;
import com.hro.hro_app.main.MyApplication;
import com.hro.hro_app.main.RoosterDataChanged;
import com.hro.hro_app.model.Lesson;
import com.hro.hro_app.model.Teacher;
import com.hro.hro_app.util.DateUtil;

public class LessonController {

	public static void refreshData(RoosterDataChanged downloadRoosterListener) {

		try {

			Context[] params = new Context[1];
			params[0] = MyApplication.getAppContext();

			DownloadRoosterTask task = new DownloadRoosterTask(downloadRoosterListener);
			task.execute(params);
		}
		catch (Exception e) {
			Log.e(LessonController.class.getName(), e.toString());
		}
	}

	public static void deleteTable() {

		DBManager dbManager = null;
		SQLiteDatabase db = null;

		try {

			dbManager = new DBManager(MyApplication.getAppContext());
			db = dbManager.getWritableDatabase();
			db.delete("rooster", null, null);
		}
		finally {

			if (db != null)
				db.close();
			if (dbManager != null)
				dbManager.close();
		}
	}

	public static void saveLesson(Lesson lesson) {

		DBManager dbManager = null;
		SQLiteDatabase db = null;

		try {

			dbManager = new DBManager(MyApplication.getAppContext());
			db = dbManager.getWritableDatabase();

			ContentValues values = new ContentValues();
			values.put("_uid", lesson.getLessonId());
			values.put("start", lesson.getStart().getTime());
			values.put("end", lesson.getEnd().getTime());
			values.put("teacher", lesson.getTeacher());
			values.put("module", lesson.getModule());
			values.put("location", lesson.getLocation());

			// Insert into database
			db.insertWithOnConflict("rooster", null, values, SQLiteDatabase.CONFLICT_REPLACE);
		}
		finally {

			if (db != null)
				db.close();
			if (dbManager != null)
				dbManager.close();
		}
	}

	public static Lesson getNextlesson() {

		DBManager dbManager = null;
		SQLiteDatabase db = null;
		Cursor cursor = null;

		try {

			Date curdate = new Date();

			dbManager = new DBManager(MyApplication.getAppContext());
			db = dbManager.getWritableDatabase();
			cursor = db.rawQuery("SELECT * FROM rooster WHERE start > '" + curdate.getTime() + "' ORDER BY start ASC LIMIT 1", null);

			if (cursor.getCount() == 0) {
				return null;
			}
			else {

				cursor.moveToFirst();

				String lessonId = cursor.getString(cursor.getColumnIndex("_uid"));
				String module = cursor.getString(cursor.getColumnIndex("module"));
				String teacher = cursor.getString(cursor.getColumnIndex("teacher"));
				String location = cursor.getString(cursor.getColumnIndex("location"));
				SimpleDateFormat sourceFormat = new SimpleDateFormat();
				sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

				// 1Date parsed = format.parse("2011-03-01 15:10:37"); // => Date is in UTC now
				Long lstart = cursor.getLong(cursor.getColumnIndex("start"));
				Date start = new Date(lstart);
				// = new Date(cursor.getLong(cursor.getColumnIndex(LessonDBManager.C_START)));
				Date end = new Date(cursor.getLong(cursor.getColumnIndex("end")));

				Lesson nextLesson = new Lesson(lessonId, module, teacher, location, start, end);
				return nextLesson;
			}
		}
		finally {

			if (cursor != null)
				cursor.close();
			if (db != null)
				db.close();
			if (dbManager != null)
				dbManager.close();
		}
	}

	public static ArrayList<Teacher> getAllTeachers() {

		DBManager dbManager = null;
		SQLiteDatabase db = null;
		Cursor cursor = null;

		ArrayList<Teacher> teachers = new ArrayList<Teacher>();

		try {

			dbManager = new DBManager(MyApplication.getAppContext());
			db = dbManager.getWritableDatabase();
			cursor = db.rawQuery("SELECT DISTINCT teacher FROM rooster ORDER BY teacher DESC", null);

			while (cursor.moveToNext()) {

				String teachCode = cursor.getString(cursor.getColumnIndex("teacher"));
				Teacher teacher = new Teacher(teachCode);
				teachers.add(teacher);
			}

			return teachers;
		}
		finally {

			if (cursor != null)
				cursor.close();
			if (db != null)
				db.close();
			if (dbManager != null)
				dbManager.close();
		}
	}

	public static Date getNextLesDay() {

		Date returndate;
		DBManager dbManager = null;
		SQLiteDatabase db = null;
		Cursor cursor = null;

		try {

			dbManager = new DBManager(MyApplication.getAppContext());
			db = dbManager.getWritableDatabase();
			Date today = new Date();
			cursor = db.rawQuery("SELECT  start FROM rooster WHERE start > ? ORDER BY start ASC LIMIT 1", new String[] { Long.toString(today.getTime()) });
			cursor.moveToNext();
			returndate = new Date(cursor.getLong(0));
		}
		finally {
			if (cursor != null)
				cursor.close();
			if (db != null)
				db.close();
			if (dbManager != null)
				dbManager.close();
		}

		returndate = DateUtil.removeTimeInfo(returndate);
		return returndate;
	}

	public static ArrayList<Lesson> getLessonsByDay(Date lesday) {

		DBManager dbManager = null;
		SQLiteDatabase db = null;
		Cursor cursor = null;

		ArrayList<Lesson> lessons = new ArrayList<Lesson>();

		try {

			dbManager = new DBManager(MyApplication.getAppContext());
			db = dbManager.getWritableDatabase();
			// Maak parameters
			String fromStart = Long.toString(lesday.getTime());
			String toEnd = Long.toString(DateUtil.addDays(lesday, 1).getTime());
			String[] selArgs = new String[] { fromStart, toEnd };

			cursor = db.rawQuery("SELECT * FROM rooster WHERE start > ? AND end < ? ORDER BY start ASC", selArgs);

			while (cursor.moveToNext()) {

				String lessonId = cursor.getString(cursor.getColumnIndex("_uid"));
				String module = cursor.getString(cursor.getColumnIndex("module"));
				String teacher = cursor.getString(cursor.getColumnIndex("teacher"));
				String location = cursor.getString(cursor.getColumnIndex("location"));
				SimpleDateFormat sourceFormat = new SimpleDateFormat();
				sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

				// 1Date parsed = format.parse("2011-03-01 15:10:37"); // => Date is in UTC now
				Long lstart = cursor.getLong(cursor.getColumnIndex("start"));
				Date start = new Date(lstart);
				// = new Date(cursor.getLong(cursor.getColumnIndex(LessonDBManager.C_START)));
				Date end = new Date(cursor.getLong(cursor.getColumnIndex("end")));

				Lesson lesson = new Lesson(lessonId, module, teacher, location, start, end);
				lessons.add(lesson);
			}

			return lessons;
		}
		finally {

			if (cursor != null)
				cursor.close();
			if (db != null)
				db.close();
			if (dbManager != null)
				dbManager.close();
		}
	}

	public static int LessonCount() {

		DBManager dbManager = new DBManager(MyApplication.getAppContext());
		SQLiteDatabase db = dbManager.getWritableDatabase();
		Cursor cursor = null;

		try {

			cursor = db.rawQuery("SELECT count(*) FROM rooster", null);
			cursor.moveToFirst();

			return cursor.getInt(0);
		}
		finally {

			if (cursor != null)
				cursor.close();
			if (db != null)
				db.close();
			if (dbManager != null)
				dbManager.close();
		}
	}
}